<?php

/**
 * 新闻资讯管理
 */

namespace app\ph\controller;

class Content extends Base
{
    protected $content_model;
    protected $tag_model;

    public function __construct()
    {
        parent::__construct();
        $this->content_model = new \app\common\model\Content();
        $this->tag_model     = new \app\common\model\Tag();
    }

    /**
     * 列表功能
     * @return \think\response\View
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $where = [];
        $title = input("get.title");
        $title && $where[] = ['c.title', 'like', "%$title%"];
        $field = 'n.title as cat_title,c.id,c.title,c.views,c.create_time,c.link';
        $data  = $this->content_model->getList($where, $field);
        $page  = $data->render();
        $data  = $data->items();
        return view('content/index',
            [
                'data'  => $data,
                'page'  => $page,
                'title' => $title
            ]
        );
    }

    /**
     * 添加
     * @return \think\response\View
     */
    public function data_insert()
    {
        $nav = \app\common\model\Nav::where(['type' => 0])->field('id,title')->select();
        return view('content/data_insert',
            [
                'nav' => $nav
            ]
        );
    }

    /**
     * 修改
     * @param $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function data_update($id)
    {
        if (!$id) {
            $this->error('缺失参数ID');
        }
        $data = $this->content_model->getOne(['id' => $id], '*', 'id desc');
        if (!$data) {
            $this->error('获取信息失败');
        }
        $data['tag'] = mb_substr($data['tag'], 1, -1);
        $nav         = \app\common\model\Nav::where(['type' => 0])->field('id,title')->select();
        return view('content/data_update',
            [
                'data' => $data,
                'nav'  => $nav
            ]
        );
    }

    /**
     * 数据操作
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function data_save()
    {
        $data['title']     = input('post.title');
        $data['views']     = input('post.views');
        $data['tag']       = input('post.tag') ? "，" . input('post.tag') . '，' : '';
        $data['tag_id']    = $this->getTagData(input('post.tag'));
        $data['keywords']  = input('post.keywords');
        $data['content']   = htmlspecialchars_decode(input('post.content'));
        $data['represent'] = input('post.represent');
        if (!$data['represent']) {
            $data['represent'] = mb_substr(trim(strip_tags($data['content'])), 0, 300);
        }
        $data['cover']     = input('post.cover');
        $data['type']      = input('post.type');
        $data['recommend'] = input('post.recommend');
        $data['status']    = input('post.status');
        $viewRand          = input('post.view_rand');
        if ($viewRand) {
            $data['views'] = rand(50, 100);
        }
        $data['create_time'] = strtotime(input('post.create_time')) ? strtotime(input('post.create_time')) : time();

        $id              = input('post.id');
        $data['content'] = $this->changeTag($data['content']);
        if ($id) {
            $data['update_time'] = time();
            $res                 = $this->content_model->editData(['id' => $id], $data);
        } else {
            // 增加缓存
            $res = \app\common\model\Content::create($data);
            $id  = $res['id'];
        }
        // 修改link链接地址
        $link = $this->getLinkData($id, $data['type']);
        $this->content_model->editData(['id' => $id], ['link' => $link]);
        return operationResult($res, url('Content/Index'));
    }

    /**
     * 替换标签
     * @param $content
     * @return string|string[]
     */
    public function changeTag($content)
    {
        $tag = \app\common\model\Tag::field('id', 'title')->order('id desc')->select();
        foreach ($tag as $k => $v) {
            $content = str_replace($v['title'], '<a href="/tag-' . $v['id'] . '/" title="' . $v['title'] . '">' . $v['title'] . '</a>', $content);
        }
        return $content;
    }

    /**
     * 获取正确链接地址
     * @param $id
     * @param $type
     * @return string
     */
    private function getLinkData($id, $type)
    {
        $path = \app\common\model\Nav::where(['id' => $type])->value('path');
        return '/' . $path . $id . '.html';
    }

    /**
     * 获取 TAG ID
     * @param $tag
     * @return string
     */
    private function getTagData($tag)
    {
        if (!$tag) {
            return '';
        }
        $tagId   = '，';
        $tagData = explode('，', $tag);
        foreach ($tagData as $k => $v) {
            $id = \app\common\model\Tag::where(['title' => $v])->value("id");
            if (!$id) {
                $insertData = \app\common\model\Tag::create(['title' => $v]);
                $tagId      .= $insertData['id'] . '，';
            } else {
                $tagId .= $id . '，';
            }
        }
        return $tagId;
    }

    /**
     * 删除
     * @return \think\response\Json
     */
    public function data_delete()
    {
        $id = input('post.id');
        if (!$id) {
            return json(['code' => 100, 'message' => '缺失ID参数']);
        }
        $res = $this->content_model->dataDelete($id);
        return operationResult($res);
    }

    /**
     * 历史封面图片
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function img()
    {
        $this->view->engine->layout(false);
        $data = $this->content_model->getAll([], 'cover');
        return view('content/img',
            [
                'data' => $data
            ]
        );
    }
}
